import time

import win32gui
import win32con
import win32api


def find_window_by_title(title):
    """Finds the handle of a window by its title."""
    return win32gui.FindWindow(None, title)


def get_child_classes(parent_hwnd):
    """
    遍历指定父窗口的所有直接子窗口，并返回它们的类名列表。
    Args:
        parent_hwnd: 父窗口的句柄 (HWND).
    Returns:
        一个包含所有子窗口类名的列表。
    """
    child_classes = []

    def enum_child_callback(hwnd, arg):
        """
        EnumChildWindows 的回调函数，用于处理每个子窗口。
        """
        class_name = win32gui.GetClassName(hwnd)
        child_classes.append(class_name)
        return True  # 继续枚举下一个子窗口

    win32gui.EnumChildWindows(parent_hwnd, enum_child_callback, None)
    return child_classes


def click_botton_right_button_in_window(window_title):
    """Finds a window by title and clicks an 'OK' button within it."""
    main_window_hwnd = find_window_by_title(window_title)

    if not main_window_hwnd:
        print(f"Window with title '{window_title}' not found.")
        return -1
    else:
        print(f"find windows by {window_title}, hwnd: {main_window_hwnd}")

    win32gui.SetForegroundWindow(main_window_hwnd)

    # calc position of the sreen point
    rect = win32gui.GetClientRect(main_window_hwnd)
    width = rect[2] - rect[0]
    height = rect[3] - rect[1]

    # 0.0 represents edge
    # 1.0 represents the other edge
    relative_x = 0.9
    relative_y = 0.9
    click_x = int(width * relative_x)
    click_y = int(height * relative_y)
    client_point = (click_x, click_y)
    screen_point = win32gui.ClientToScreen(main_window_hwnd, client_point)
    print(screen_point)
    # mouse click
    mouse_event_flags = win32con.MOUSEEVENTF_LEFTDOWN | win32con.MOUSEEVENTF_LEFTUP
    win32api.SetCursorPos(screen_point)  # 可选: 将鼠标移动到点击位置
    win32api.mouse_event(mouse_event_flags, screen_point[0], screen_point[1], 0, 0)


if __name__ == "__main__":
    target_window_title = "Import DevEco Studio Settings"  # Replace with the actual window title
    click_botton_right_button_in_window(target_window_title)
    time.sleep(2)
    win_title = "Welcome to HUAWEI DevEco Studio"
    click_botton_right_button_in_window(win_title)
